<template>
  <div class="addressCascader_module wfull">
    <el-cascader
      clearable
      class="wfull"
      v-model="localModelValue"
      :options="options"
      :props="cascaderProps"
      @change="handleChange"
      filterable
      :disabled="disabled"
      :placeholder="$t(placeholderKey)"
    />
  </div>
</template>

<script lang="ts">
import { defineComponent, ref,watch } from "vue";
import { CascaderProps } from 'element-plus';
import { regionData,DataItem } from "element-china-area-data";
export default defineComponent({
  name: "addressCascader",
  props: {
    cascaderProps: {
        type: Object as () => CascaderProps,
        default: () => {return {expandTrigger: "hover" as const}}
    },
    // 新增：接收父组件传递的初始选中地址值
    modelValue: {
      type: Array as () => string[],
      default: () => []
    },
    // 是否禁用
    disabled: {
        type: Boolean,
        default: () => false
    },
    placeholderKey: {
        type: String,
        default: () => "clueInformation_customerAddress_placeholder"
    }
  },
  setup(props,{emit}) {
    
    // 获取标签设置
    const getLabels = (options:DataItem[], selectedValues:string[],labels:string[]) => {
      if (!selectedValues) {
        return labels
      }
        for (let i = 0; i < options.length; i++) {
            if (selectedValues[0] === options[i].value) {
                labels.push(options[i].label);
                if (selectedValues.length > 1 && options[i].children) {
                    getLabels(options[i].children as DataItem[], selectedValues.slice(1),labels);
                }
                break;
            }
        }
        return labels
    };
    const options = ref(regionData);
    const localModelValue = ref<string[]>(props.modelValue);
    const handleChange = (payload:string[]) => {
      localModelValue.value = payload
      
      let labels = getLabels(options.value,payload,[])
      emit("getLabels",labels)
      emit("update:modelValue",payload)
    };

    watch(() => props.modelValue,(newVal) => {
      localModelValue.value = newVal
      let labels = getLabels(options.value,localModelValue.value,[])
      emit("getLabels",labels)
    })

    return {
      options,
      handleChange,
      localModelValue,
    };
  },
});
</script>
<style scoped></style>
